#include<bits/stdc++.h>
using namespace std;
const int N=1005;
inline int read(){
	int x=0,f=1;char ch=getchar();
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch)){x=(x<<1)+(x<<3)+ch-48,ch=getchar();}
	return x*f;
}

int T,n,mod,a[N][N],b[N][N],c[N][N],d[N][N];

inline void Mod(int &x,int y){((x+=y)>=mod)?x-=mod:0;}

signed main(){
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	T=read();
	while(T--){
		mod=read(),n=read();
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				a[i][j]=read();
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				b[i][j]=read();
		for(int i=1;i<=n;++i)
			for(int j=1;j<=n;++j)
				c[i][j]=read();
                
        bool flg=1;
		for(int i=1;i<=n;++i){
			for(int j=1;j<=n;++j){
				d[i][j]=0;
				for(int k=1;k<=n;++k)
					Mod(d[i][j],1ll*a[i][k]*b[k][j]%mod);	
                if(c[i][j]^d[i][j])
					flg=0,i=n+1,j=n+1;			
			}
		}
				
		flg?puts("Yes"):puts("No");
	}
	return 0;
}